import routeSettings from './dynamic.json'
// import { LOGIN_URL } from '@/config'
// import { useAuthStore } from '@/store/modules/auth'

const clientModules = import.meta.glob(`@/pages/__client-dynamic/**/*.vue`)

const deepSetter = (targets) => {
  if(!targets.length) {
    return []
  }
  const routes = []
  targets.forEach(async (setting) => {
    let component, meta = {}, match = setting.path
    if(setting.componentPath) {
      match = setting.componentPath
    }
    if(setting.meta) {
      meta = Object.assign({}, setting.meta)
    }
    component = clientModules[`/src/pages/__client-dynamic${match}.vue`] || null
    if(component) {
      // component().then((resolve) => {
      //   const { pageMeta = {} } = resolve.default
      //   meta = Object.assign(meta, pageMeta)
      //   routes.push({
      //     path: `${setting.path}`,
      //     name: meta.title || setting.path,
      //     component: resolve.default,
      //     meta,
      //     children: deepSetter(setting.children || []),
      //   })
      // })
      routes.push({
        path: `${setting.path}`,
        name: meta.title || setting.path,
        component,
        meta,
        children: deepSetter(setting.children || []),
      })
    }
  })
  return routes
}

export async function setupClientDynamicRouter(router) {
  const routes = deepSetter(routeSettings)
  routes.forEach((route) => {
    !router.hasRoute(route.name) && router.addRoute('layout', route)
  })
}
